#!/system/bin/sh
# set -e -u

SCRIPTNAME=termux-usb
show_usage () {
    echo "Usage: $SCRIPTNAME [-l | [-r] [-E] [-e command] [device | vendorId productId]]"
    echo "List or access USB devices. Devices cannot be accessed directly,"
    echo "                 only using $SCRIPTNAME."
    echo "  -l           list available devices"
    echo "  -r           show permission request dialog if necessary"
    echo "  -e command   execute the specified command with a file descriptor"
    echo "                 referring to the device as an argument (unless -E"
    echo "                 argument is given)"
    echo "  -E           transfer file descriptor as env var instead of as"
    echo "                 command line argument"
    exit 0
}

ACTION="permission"
PARAMS=""
while getopts :hlre:E option
do
    case "$option" in
        h) show_usage;;
        l) ACTION="list";;
        r) PARAMS="$PARAMS --ez request true";;
        e) ACTION="open"; export TERMUX_CALLBACK="$OPTARG";;
        E) export TERMUX_EXPORT_FD=true;;
        ?) echo "$SCRIPTNAME: illegal option -$OPTARG"; exit 1;
    esac
done
shift $((OPTIND-1))

if [ "$ACTION" == "list" ]
then
    if [ $# -gt 0 ]; then echo "$SCRIPTNAME: too many arguments"; exit 1; fi
else
    if [ $# -lt 1 ]; then
        echo "$SCRIPTNAME: missing -l or device path"
        exit 1
    elif [ $# -eq 1 ]; then
        # The device's usbfs path has been provided
        PARAMS="$PARAMS --es device $1"
    elif [ $# -eq 2 ]; then
        # A vendorId and ProductId of the device has been provided
        PARAMS="$PARAMS --es vendorId $1"
        PARAMS="$PARAMS --es productId $2"
    else
        echo "$SCRIPTNAME: too many arguments"
        exit 1
    fi
fi
# echo "TERMUX_CALLBACK:$TERMUX_CALLBACK"
# echo "TERMUX_EXPORT_FD:$TERMUX_EXPORT_FD"
CMD="termux-api Usb -a $ACTION $PARAMS"
# termux-toast "CMD:$CMD"
# echo "CMD:$CMD"

if [ "$ACTION" == "permission" ]
then
    if [ "$($CMD)" == "yes" ]
    then
        echo "Access granted."
        exit 0
    else
        echo "Access denied."
        exit 1
    fi
else
    $CMD
fi

